import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';

class VoiceRecordBar extends StatefulWidget {
  const VoiceRecordBar({
    Key? key,
    this.onStartRecord,
    this.onStopRecord,
    this.onCancelRecord,
    this.isRecording = false,
    this.recordDuration = 0,
  }) : super(key: key);

  final VoidCallback? onStartRecord;
  final VoidCallback? onStopRecord;
  final VoidCallback? onCancelRecord;
  final bool isRecording;
  final int recordDuration;

  @override
  State<VoiceRecordBar> createState() => _VoiceRecordBarState();
}

class _VoiceRecordBarState extends State<VoiceRecordBar>
    with TickerProviderStateMixin {
  bool _isCancelling = false;
  double _slideDistance = 0.0;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(VoiceRecordBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isRecording && !oldWidget.isRecording) {
      _animationController.repeat(reverse: true);
    } else if (!widget.isRecording && oldWidget.isRecording) {
      _animationController.stop();
      _animationController.reset();
    }
  }

  String get _displayText {
    if (!widget.isRecording) {
      return StrRes.holdTalk;
    }
    
    if (_isCancelling) {
      return StrRes.releaseToCancel;
    }
    
    return StrRes.releaseToSend;
  }

  String get _durationText {
    if (widget.recordDuration <= 0) return '';
    final minutes = widget.recordDuration ~/ 60;
    final seconds = widget.recordDuration % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  Color get _backgroundColor {
    if (_isCancelling) {
      return Styles.c_FF4444;
    }
    return widget.isRecording ? Styles.c_0089FF : Styles.c_FFFFFF;
  }

  Color get _textColor {
    if (_isCancelling || widget.isRecording) {
      return Styles.c_FFFFFF;
    }
    return Styles.c_0C1C33;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.h),
      height: 36.h,
      decoration: BoxDecoration(
        color: _backgroundColor,
        borderRadius: BorderRadius.circular(4.r),
        border: Border.all(
          color: widget.isRecording ? Colors.transparent : Styles.c_E8EAEF,
          width: 1.w,
        ),
      ),
      child: GestureDetector(
        onLongPressStart: _onLongPressStart,
        onLongPressEnd: _onLongPressEnd,
        onLongPressMoveUpdate: _onLongPressMoveUpdate,
        child: AnimatedBuilder(
          animation: _scaleAnimation,
          builder: (context, child) {
            return Transform.scale(
              scale: widget.isRecording ? _scaleAnimation.value : 1.0,
              child: Container(
                width: double.infinity,
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (widget.isRecording) ...[
                      Icon(
                        Icons.mic,
                        color: _textColor,
                        size: 16.w,
                      ),
                      8.horizontalSpace,
                    ],
                    Text(
                      _displayText,
                      style: TextStyle(
                        color: _textColor,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    if (widget.isRecording && widget.recordDuration > 0) ...[
                      8.horizontalSpace,
                      Text(
                        _durationText,
                        style: TextStyle(
                          color: _textColor,
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  void _onLongPressStart(LongPressStartDetails details) {
    _isCancelling = false;
    _slideDistance = 0.0;
    widget.onStartRecord?.call();
    setState(() {});
  }

  void _onLongPressEnd(LongPressEndDetails details) {
    if (_isCancelling) {
      widget.onCancelRecord?.call();
    } else {
      widget.onStopRecord?.call();
    }
    _isCancelling = false;
    _slideDistance = 0.0;
    setState(() {});
  }

  void _onLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
    _slideDistance = details.localPosition.dy;
    final shouldCancel = _slideDistance < -50.h;
    
    if (shouldCancel != _isCancelling) {
      setState(() {
        _isCancelling = shouldCancel;
      });
      if (_isCancelling) {
        HapticFeedback.lightImpact();
      }
    }
  }
}